package com.cdyZuul.ZuulFilter;

import entity.IpRuleChecker;
import entity.IpUtil;
import com.cdyZuul.tool.RouteLocatorUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * ip黑名单过滤器。当开启了EnableBlackList时才启用
 *
 */
//@Component
public class WhileListFiltert extends ZuulFilter {
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Resource
    private IpRuleChecker ipRuleChecker;
    @Resource
    private RouteLocator routeLocator;

    @Override
    public String filterType() {
        return  FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //让该filter位置靠前
        return -101;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        if (ipRuleChecker == null) {
            return null;
        }

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest serverHttpRequest = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();

        String userIp = IpUtil.getIpAddress(serverHttpRequest);
        boolean isWhite = ipRuleChecker.check(userIp);
        if (!isWhite) {
            //解析出请求的app名字
            String appName = RouteLocatorUtil.parseAppNameAndPath(routeLocator, serverHttpRequest)[0];
            //这些被排除的APP，黑名单也允许访问
            Set<String> exceptApps = ipRuleChecker.exceptApps();
            if (!CollectionUtils.isEmpty(exceptApps) && exceptApps.contains(appName)) {

                return null;
            } else {
                requestContext.setSendZuulResponse(false);
                response.setStatus(404);
                requestContext.setResponseBody(userIp+"not in the WhileLis!");
            }
        }

        return null;
    }
}
